package com.feimt.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feimt.pojo.Employee;
import com.feimt.result.R;
import com.feimt.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;

/**
 * @author 宋孟林
 * @description
 */
@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {

    private final EmployeeService employeeService;

    @Autowired
    public EmployeeController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    /**
     * 登录控制器方法，传入参数employee用于登录验证，首先将employee打印到控制台，再将密码加密后和数据库进行比对
     * 通过条件查询封装器mybatis的封装方法getOne来查询到这个员工对象后返回这个对象，同时在这之前，将员工的id用session保存到属性auth中
     * @param employee 登陆的员工对象
     * @param session 保存属性的绘画对象
     * @return 返回对象
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
//        log.info("employee:{}", employee);
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(wrapper);
        if (emp == null){
            return R.error("登陆失败");
        }
        if (!emp.getPassword().equals(password)){
            return R.error("登陆失败");
        }
        if (emp.getStatus() == 0){
            return R.error("员工已被禁用");
        }
        session.setAttribute("auth", emp.getId());
        return R.success(emp);
    }

    /**
     * 登出，将auth属性移除就登出了
     * @param request 获取属性
     * @return 返回退出成功字符串
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("auth");
        return R.success("退出成功");
    }

    /**
     * 添加员工，加密员工的密码，设置员工的状态，返回是否新增成功
     * @param employee 1
     * @param session 1
     * @param request 1
     * @return 1
     */
    @PostMapping
    public R<Object> add(@RequestBody Employee employee,HttpSession session, HttpServletRequest request){
//        log.info("employee:{}", employee);
//        log.info("request method is :{}", request.getMethod());
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        Long auth = (Long) session.getAttribute("auth");
//        employee.setCreateUser(auth);
//        employee.setUpdateUser(auth);
        employee.setStatus(1);
        boolean flag = employeeService.save(employee);
        return flag ? R.success("新增成功") : R.error("新增失败");
    }

    /**
     * 员工管理分页实现方法，先创建分页对象，在创建条件查询器，根据姓名模糊查询是否存在这些员工，再分别按照更新时间和名字排序
     * service调用page方法来查询数据，将查询结果返回
     * @param page 页号
     * @param pageSize 页容量
     * @param name 模糊查询名
     * @return 返回分页数据集合
     */
    @GetMapping("/page")
    public R<Object> page(Integer page, Integer pageSize, String name){
        Page<Employee> employeePage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null && !"".equals(name), Employee::getName, name);
        wrapper.orderByDesc(Employee::getUpdateTime).orderByAsc(Employee::getName);
        employeeService.page(employeePage, wrapper);
        return R.success(employeePage);
    }

    /**
     * 使用当前对象作为service对象调用updateById方法的参数返回是否修改成功的变量
     * @param employee 当前员工
     * @param session 获取属性
     * @return 返回是否修改成功
     */
    @PutMapping
    public R <String> update(@RequestBody Employee employee, HttpSession session){
        log.info("修改employee:{}", employee);
//        employee.setUpdateTime(LocalDateTime.now());
//        Long auth = (Long)session.getAttribute("auth");
//        employee.setUpdateUser(auth);
        boolean b = employeeService.updateById(employee);
        return b ? R.success("修改成功") : R.error("修改错误");
    }

    /**
     * 根据id查询员工成功后返回这个员工对象,在前端编辑员工信息时，回显数据到前端中
     * @param id 输入的id
     * @return 返回员工对象
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable("id") Long id){
//        log.info("id:{}", id);
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }
}
